#include "maintain_buttondelegate.h"

#include <QWidget>
#include <QScreen>
#include <QApplication>
#include <QMouseEvent>
#include <QDialog>
#include <QPainter>
#include <QStyleOption>
#include <QDesktopWidget>

MaintainButtonDelegate::MaintainButtonDelegate(QObject *parent) :
    QItemDelegate(parent)
{
}

void MaintainButtonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionButton* pButton = m_mapButton.value(index);
    if (!pButton) {
        pButton = new QStyleOptionButton();
        pButton->rect = option.rect.adjusted(4, 4, -4, -4);
        pButton->text = "QC";
        pButton->state |= QStyle::State_Enabled;

        (const_cast<MaintainButtonDelegate *>(this))->m_mapButton.insert(index, pButton);
    }

    painter->save();
    if (option.state & QStyle::State_Selected) {
        painter->fillRect(option.rect, option.palette.highlight());
    }

    painter->restore();
    QApplication::style()->drawControl(QStyle::CE_PushButton, pButton, painter);
}

bool MaintainButtonDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if (event->type() == QEvent::MouseButtonPress) {
        QMouseEvent* e =(QMouseEvent*)event;

        if (option.rect.adjusted(4, 4, -4, -4).contains(e->x(), e->y()) && m_mapButton.contains(index)) {
            m_mapButton.value(index)->state |= QStyle::State_Sunken;
        }
    }

    if (event->type() == QEvent::MouseButtonRelease) {
        QMouseEvent* e =(QMouseEvent*)event;

        if (option.rect.adjusted(4, 4, -4, -4).contains(e->x(), e->y()) && m_mapButton.contains(index)) {
            m_mapButton.value(index)->state &= (~QStyle::State_Sunken);

            // Startup test
            emit signalButtonClicked(model->data(index).toInt() - 1, true);
        }
    }

    return QItemDelegate::editorEvent(event, model, option, index);
}

void MaintainButtonDelegate::slotProgressFinished(int nRowIdx)
{
    Q_UNUSED(nRowIdx);
}
